package com.yupi.springbootinit.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.mapper.OperationMapper;
import com.yupi.springbootinit.model.dto.operation.OperationQueryRequest;
import com.yupi.springbootinit.model.entity.Operation;
import com.yupi.springbootinit.model.vo.OperationVO;
import com.yupi.springbootinit.service.OperationService;
import com.yupi.springbootinit.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 工序库服务实现
 */
@Service
@Slf4j
public class OperationServiceImpl extends ServiceImpl<OperationMapper, Operation> implements OperationService {

    @Override
    public void validOperation(Operation operation, boolean add) {
        if (operation == null) {
            throw new RuntimeException("工序库信息不能为空");
        }
        String operationCode = operation.getOperationCode();
        String operationName = operation.getOperationName();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(operationCode, operationName), ErrorCode.PARAMS_ERROR, "工序编码和工序名称不能为空");
            
            // 检查工序编码是否重复
            QueryWrapper<Operation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("operationCode", operationCode);
            long count = this.count(queryWrapper);
            if (count > 0) {
                throw new RuntimeException("工序编码已存在");
            }
        } else {
            // 更新时检查工序编码是否与其他记录重复
            if (StringUtils.isNotBlank(operationCode) && operation.getId() != null) {
                QueryWrapper<Operation> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("operationCode", operationCode);
                queryWrapper.ne("id", operation.getId());
                long count = this.count(queryWrapper);
                if (count > 0) {
                    throw new RuntimeException("工序编码已存在");
                }
            }
        }
    }

    @Override
    public QueryWrapper<Operation> getQueryWrapper(OperationQueryRequest operationQueryRequest) {
        QueryWrapper<Operation> queryWrapper = new QueryWrapper<>();
        if (operationQueryRequest == null) {
            return queryWrapper;
        }
        String operationCode = operationQueryRequest.getOperationCode();
        String operationName = operationQueryRequest.getOperationName();
        String equipmentType = operationQueryRequest.getEquipmentType();
        String skillLevel = operationQueryRequest.getSkillLevel();
        String sortField = operationQueryRequest.getSortField();
        String sortOrder = operationQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(operationCode), "operationCode", operationCode);
        queryWrapper.like(StringUtils.isNotBlank(operationName), "operationName", operationName);
        queryWrapper.like(StringUtils.isNotBlank(equipmentType), "equipmentType", equipmentType);
        queryWrapper.like(StringUtils.isNotBlank(skillLevel), "skillLevel", skillLevel);
        
        // 排序处理，避免空指针异常
        if (StringUtils.isNotBlank(sortField) && StringUtils.isNotBlank(sortOrder)) {
            queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals("ascend"), sortField);
        } else {
            // 默认按创建时间倒序排列
            queryWrapper.orderByDesc("createTime");
        }
        return queryWrapper;
    }

    @Override
    public OperationVO getOperationVO(Operation operation) {
        if (operation == null) {
            return null;
        }
        OperationVO operationVO = new OperationVO();
        BeanUtils.copyProperties(operation, operationVO);
        return operationVO;
    }

    @Override
    public Page<OperationVO> getOperationVOPage(Page<Operation> operationPage) {
        List<Operation> operationList = operationPage.getRecords();
        Page<OperationVO> operationVOPage = new Page<>(operationPage.getCurrent(), operationPage.getSize(), operationPage.getTotal());
        if (CollUtil.isEmpty(operationList)) {
            return operationVOPage;
        }
        // 填充信息
        List<OperationVO> operationVOList = operationList.stream().map(this::getOperationVO).collect(Collectors.toList());
        operationVOPage.setRecords(operationVOList);
        return operationVOPage;
    }
}